package gui;

import entity.Score;
import entity.Student;
import service.FileManager;
import service.ScoreManager;
import service.StudentManager;

import javax.swing.*;
import java.awt.*;
import java.util.Map;

/**
 * 数据管理面板
 */
public class DataPanel extends JPanel {
    private final FileManager fileManager;
    private final ScoreManager scoreManager;
    private final StudentManager studentManager;
    
    // UI组件
    private JButton saveStudentButton, saveScoreButton;
    private JButton loadStudentButton, loadScoreButton;
    private JButton backupButton;
    private JTextArea logArea;
    
    /**
     * 构造函数
     */
    public DataPanel(FileManager fileManager, ScoreManager scoreManager, StudentManager studentManager) {
        this.fileManager = fileManager;
        this.scoreManager = scoreManager;
        this.studentManager = studentManager;
        initUI();
    }
    
    /**
     * 初始化UI
     */
    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 创建日志面板
        JPanel logPanel = createLogPanel();
        
        // 添加组件到面板
        add(buttonPanel, BorderLayout.NORTH);
        add(logPanel, BorderLayout.CENTER);
    }
    
    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("数据操作"));
        
        // 创建按钮
        saveStudentButton = new JButton("保存学生数据");
        saveScoreButton = new JButton("保存成绩数据");
        loadStudentButton = new JButton("加载学生数据");
        loadScoreButton = new JButton("加载成绩数据");
        backupButton = new JButton("备份所有数据");
        JButton clearLogButton = new JButton("清空日志");
        
        // 添加按钮事件
        saveStudentButton.addActionListener(e -> saveStudentData());
        saveScoreButton.addActionListener(e -> saveScoreData());
        loadStudentButton.addActionListener(e -> loadStudentData());
        loadScoreButton.addActionListener(e -> loadScoreData());
        backupButton.addActionListener(e -> backupData());
        clearLogButton.addActionListener(e -> logArea.setText(""));
        
        // 添加按钮到面板
        panel.add(saveStudentButton);
        panel.add(saveScoreButton);
        panel.add(loadStudentButton);
        panel.add(loadScoreButton);
        panel.add(backupButton);
        panel.add(clearLogButton);
        
        return panel;
    }
    
    /**
     * 创建日志面板
     */
    private JPanel createLogPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("操作日志"));
        
        // 创建日志文本区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        logArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        
        // 添加滚动条
        JScrollPane scrollPane = new JScrollPane(logArea);
        
        // 添加组件到面板
        panel.add(scrollPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 保存学生数据
     */
    private void saveStudentData() {
        try {
            fileManager.saveStudent(studentManager.getStudentMap());
            appendLog("学生数据保存成功！");
        } catch (Exception e) {
            appendLog("错误: 保存学生数据失败 - " + e.getMessage());
            JOptionPane.showMessageDialog(this, "保存学生数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 保存成绩数据
     */
    private void saveScoreData() {
        try {
            fileManager.saveScore(scoreManager.getScores());
            appendLog("成绩数据保存成功！");
        } catch (Exception e) {
            appendLog("错误: 保存成绩数据失败 - " + e.getMessage());
            JOptionPane.showMessageDialog(this, "保存成绩数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 加载学生数据
     */
    private void loadStudentData() {
        try {
            Map<String, Student> loadedStudents = fileManager.loadStudents();
            
            // 确认是否覆盖现有数据
            if (!studentManager.getStudentMap().isEmpty()) {
                int option = JOptionPane.showConfirmDialog(
                        this,
                        "加载数据将覆盖现有学生数据，是否继续？",
                        "确认加载",
                        JOptionPane.YES_NO_OPTION);
                
                if (option != JOptionPane.YES_OPTION) {
                    appendLog("已取消加载学生数据。");
                    return;
                }
            }
            
            // 更新数据
            studentManager.getStudentMap().clear();
            studentManager.getStudentMap().putAll(loadedStudents);
            
            appendLog("学生数据加载成功，共加载 " + loadedStudents.size() + " 条记录。");
        } catch (Exception e) {
            appendLog("错误: 加载学生数据失败 - " + e.getMessage());
            JOptionPane.showMessageDialog(this, "加载学生数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 加载成绩数据
     */
    private void loadScoreData() {
        try {
            Map<String, Score> loadedScores = fileManager.loadScores();
            
            // 确认是否覆盖现有数据
            if (!scoreManager.getScores().isEmpty()) {
                int option = JOptionPane.showConfirmDialog(
                        this,
                        "加载数据将覆盖现有成绩数据，是否继续？",
                        "确认加载",
                        JOptionPane.YES_NO_OPTION);
                
                if (option != JOptionPane.YES_OPTION) {
                    appendLog("已取消加载成绩数据。");
                    return;
                }
            }
            
            // 更新数据
            scoreManager.getScores().clear();
            scoreManager.getScores().putAll(loadedScores);
            
            appendLog("成绩数据加载成功，共加载 " + loadedScores.size() + " 条记录。");
        } catch (Exception e) {
            appendLog("错误: 加载成绩数据失败 - " + e.getMessage());
            JOptionPane.showMessageDialog(this, "加载成绩数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 备份数据
     */
    private void backupData() {
        try {
            fileManager.saveBackup();
            appendLog("数据备份成功！");
        } catch (Exception e) {
            appendLog("错误: 数据备份失败 - " + e.getMessage());
            JOptionPane.showMessageDialog(this, "数据备份失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 添加日志
     */
    private void appendLog(String message) {
        logArea.append(message + "\n");
        // 滚动到最后一行
        logArea.setCaretPosition(logArea.getDocument().getLength());
    }
}